<?php

namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Model;
use App\Models\BaseModel;
use App\Models\Admin\Grade;
use App\Models\Admin\Share;
use App\Models\Admin\TeamAward;
use App\Models\Admin\PayConfig;
use App\Common\ValidateHandler;
use App\Models\Member\PostageZto;
use App\Models\Member\PostageEms;
use App\Models\Admin\TotalBonusPool;
use Config;
use DB;

class Store extends BaseModel
{
    protected $fillable = [
        'id', 'title', 'describe', 'name',
        'phone', 'status', 'created_at', 'updated_at'
    ];

    // 获取店铺ID 名字 / 描述 / 负责人 / 电话 / 状态 / 创建时间
    public function getStoreText($id)
    {
        $store = $this->where('id', $id)->first();
        $store['status_cn'] = $this->statusCn($store['status']);
        return $store;
    }
    public function statusCn($status)
    {
        $str = '未知';
        switch ($status) {
            case 1:
                $str = '上线';
                break;
            case 2:
                $str = '下线';
                break;
            default:
                # code...
                break;
        }
        return $str;
    }
    public function getList($request)
    {
        $find=$this->serachStore($request);
        return $find->paginate($request['pageSize'])->toArray();
    }

    // 店铺搜索 
    private function serachStore($request){
        $data=$this;
        if(!empty($request['name'])){
            $data=$data->where('name','like','%'.$request['name'].'%');
        }
        return $data;
    }

    // 遍历店铺 确认是否设置对应模块
    public function storeCheck($store, $id)
    {
        $Grade = new Grade;
        $Share = new Share;
        $TeamAward = new TeamAward;
        $PayConfig = new PayConfig;
        $grade_data = $Grade->getListId($id, 'store_id');// 传递 ID 或 数组ID , 第二参表示以指定字段 为键 , 默认否''
        $share_data = $Share->getListId($id, 'store_id');
        $award_data = $TeamAward->getListId($id, 'store_id');
        $pay_data = $PayConfig->getListId($id, 'store_id');
        $data = $this->foreachStore($store, $grade_data, $share_data, $award_data, $pay_data);
        $data['data'] = key_val($data['data']);
        return $this->success($data);
    }

    public function foreachStore($store, $grade_data, $share_data, $award_data, $pay_data)
    {
        foreach($store['data'] as $key => $val){
            $store['data'][$key]['status_str'] = Config::get("const.store_status_str")[$val['status']];

            $store['data'][$key]['grade_data'] = empty($grade_data[$val['id']]) ? '未设置' : '已设置';
            $store['data'][$key]['grade_type'] = empty($grade_data[$val['id']]) ? 0 : 1;

            $store['data'][$key]['share_data'] = empty($share_data[$val['id']]) ? '未设置' : '已设置';
            $store['data'][$key]['share_type'] = empty($share_data[$val['id']]) ? 0 : 1;

            $store['data'][$key]['award_data'] = empty($award_data[$val['id']]) ? '未设置' : '已设置';
            $store['data'][$key]['award_type'] = empty($award_data[$val['id']]) ? 0 : 1;

            $store['data'][$key]['pay_data'] = empty($pay_data[$val['id']]) ? '未设置' : '已设置';
            $store['data'][$key]['pay_type'] = empty($pay_data[$val['id']]) ? 0 : 1;

            $store['data'][$key]['jf_data'] =  '已设置';
            $store['data'][$key]['jf_type'] = 1;
        }
        return $store;
    }

    // 店铺状态修改判定 - 上线1 调用上线修改 - 下线2 / 冻结3 直接更新
    public function changeStatus($id, $status)
    {
        if ($status == 1) {
            //判断 店铺信息是否完整 , 不完整 不允许上线
            $Grade = new Grade;
            $Share = new Share;
            $TeamAward = new TeamAward;
            $PayConfig = new PayConfig;
            $grade_data = $Grade->getListId($id, 'store_id');
            $share_data = $Share->getListId($id, 'store_id');
            $award_data = $TeamAward->getListId($id, 'store_id');
            $pay_data = $PayConfig->getListId($id, 'store_id');
            if (empty($grade_data) || empty($share_data) || empty($award_data) || empty($pay_data)) {
                return $this->error(['info' => '信息不完整!请先完善店铺信息!'], 20002);
            }
        }
        $result = $this->statusUpdate($id, $status);
        if (empty($result)) {
            return $this->error(['info' => '店铺状态变更失败!请刷新 检查店铺状态是否已经生效 或 店铺数据不存在!'], 20002);
        }else{
            return $this->success(['info' => '['.$status.']店铺状态变更成功!']);
        }
    }

    // 进行店铺状态更新
    public function statusUpdate($id, $status)
    {
        return $this->where('id', $id)->update(['status' => $status]);
    }

    // 寻找店铺信息 并 返回
    public function findStore($id)
    {
        return $this->where('id',$id)->first()->toArray();
    }

    // 插入店铺信息
    public function insertStore($data)
    {
        $arr = [];
        $arr['title'] = $data['title'];
        $arr['describe'] = empty($data['describe']) ? '' : $data['describe'];
        $arr['name'] = $data['name'];
        $arr['phone'] = $data['phone'];
        $arr['status'] = 2;
        $result=$this->validate($arr);
        if (!$result['res']) {
            return $this->error(['info' => $result['info']]);
        }
        $arr['created_at'] = date("Y-m-d H:i:s");
        DB::beginTransaction();
        try {
            $insertData=$this->insertGetId($arr);
            
            if ($insertData) {
                // 邮费信息 初始化 以 0 为原始数据开始制作 
                $PostageZto = new PostageZto;
                $insertZto = $PostageZto->insertZto($insertData);// 传递店铺ID
                if ($insertZto['code'] == 20001) {
                    return $this->error(['info' => $insertZto['info']]);
                }
                $PostageEms = new PostageEms;
                $insertEms = $PostageEms->insertEms($insertData);// 传递店铺ID
                if ($insertEms['code'] == 20001) {
                    return $this->error(['info' => $insertEms['info']]);
                }
                // 初始化 店铺各类奖金池
                $bonus = new TotalBonusPool;
                $bonusPool = $bonus->insert(['store_id'=>$insertData,'created_at'=>date('Y-m-d H:i:s')]);// 传递店铺ID

                DB::commit();
                return $this->success(['info' => '店铺添加成功!']);
            } else {
                return $this->error(['info' => '店铺插入失败!请重试!']);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $e->getLine().$e->getMessage();
        }
    }

    private function validate($data)
    {
        $arr = [
            0 => [
                'name' => '店铺名称',
                'value' => $data['title'],
                'func' => 'length_limit',
                'min' => 1,
                'max' => 10
            ],
            2 => [
                'name' => '负责人',
                'value' => $data['name'],
                'func' => 'length_limit',
                'min' => 1,
                'max' => 10
            ],
            3 => [
                'name' => '手机',
                'value' => $data['phone'],
                'func' => 'is_phone'
            ]
        ];
        if ($data['describe'] != '') {
            //店铺描述不能为空
            $arr[4] = [
                'name' => '店铺描述',
                'value' => $data['describe'],
                'func' => 'length_limit',
                'min' => 1,
                'max' => 40
            ];
        }
        return ValidateHandler::do($arr);
    }

    //更新店铺信息
    public function updateStore($data)
    {
        $arr=[];
        $arr['title'] = $data['title'];
        $arr['describe'] = empty($data['describe']) ? '' : $data['describe'];
        $arr['name'] = $data['name'];
        $arr['phone'] = $data['phone'];
        if(!empty($data['ratio'])){
            $arr['ratio'] = $data['ratio'];
        }
        
        $result=$this->validate($arr);
        if (!$result['res']) {
            return $this->error(['info' => $result['info']]);
        } 

        $update_store=$this->where('id',$data['id'])->update($arr);
        if ($update_store) {
            return $this->success(['info' => '店铺更新成功!']);
        } else {
            return $this->error(['info' => '店铺更新失败!请重试 或 刷新检查店铺是否存在!']);
        }   
    }
}
